using System.Threading.Tasks;
using UnityEngine;
using UnityEngine.Networking;
using Voodoo.Sauce.Core;
using Voodoo.Sauce.Internal;

namespace Voodoo.Sauce.Privacy
{
	public class PrivacyAPI : IPrivacyAPI
	{
		private static readonly string BaseUrl = "https://api-gdpr.voodoo-tech.io/";

		private const string NEED_CONSENT = "need_consent";

		private const string CONSENT_INSIGHTS = "consent_insights";

		private const string PRIVACY_REQUEST = "privacy_request";

		private IRequest _request;

		public void Initialize(IRequest request)
		{
			_request = request;
		}

		public Task<NeedConsent> NeedConsent(NeedConsentParams data)
		{
			TaskCompletionSource<NeedConsent> tcs = new TaskCompletionSource<NeedConsent>();
			string url = BaseUrl + "need_consent" + data;
			_request.Get(url, null, delegate(UnityWebRequest request)
			{
				NeedConsent result = null;
				try
				{
					result = JsonUtility.FromJson<NeedConsent>(request.downloadHandler.text);
				}
				catch
				{
					VoodooLog.LogError(Module.PRIVACY, "PrivacyAPI", "can't deserialize JSON");
				}
				tcs.TrySetResult(result);
			}, delegate
			{
				tcs.TrySetResult(null);
			});
			return tcs.Task;
		}

		public Task<bool> ConsentInsights(ConsentInsightsParams data)
		{
			TaskCompletionSource<bool> tcs = new TaskCompletionSource<bool>();
			string url = BaseUrl + "consent_insights" + data;
			_request.Get(url, null, delegate
			{
				tcs.TrySetResult(result: true);
			}, delegate
			{
				tcs.TrySetResult(result: false);
			});
			return tcs.Task;
		}

		public Task<PrivacyRequest> DeleteDataRequest(DeleteDataParameters p)
		{
			TaskCompletionSource<PrivacyRequest> tcs = new TaskCompletionSource<PrivacyRequest>();
			string url = BaseUrl + "privacy_request";
			string json = JsonUtility.ToJson(p);
			json = JsonUtils.AddToJson(json, "action", "delete");
			_request.PostJson(url, json, null, delegate(UnityWebRequest request)
			{
				PrivacyRequest result2 = JsonUtility.FromJson<PrivacyRequest>(request.downloadHandler.text);
				tcs.TrySetResult(result2);
			}, delegate(UnityWebRequest request)
			{
				PrivacyRequest result = JsonUtility.FromJson<PrivacyRequest>(request.downloadHandler.text);
				tcs.TrySetResult(result);
			});
			return tcs.Task;
		}

		public Task<PrivacyRequest> AccessDataRequest(AccessDataParameters p)
		{
			TaskCompletionSource<PrivacyRequest> tcs = new TaskCompletionSource<PrivacyRequest>();
			string url = BaseUrl + "privacy_request";
			string json = JsonUtility.ToJson(p);
			json = JsonUtils.AddToJson(json, "action", "access");
			_request.PostJson(url, json, null, delegate(UnityWebRequest request)
			{
				PrivacyRequest result2 = JsonUtility.FromJson<PrivacyRequest>(request.downloadHandler.text);
				tcs.TrySetResult(result2);
			}, delegate(UnityWebRequest request)
			{
				PrivacyRequest result = JsonUtility.FromJson<PrivacyRequest>(request.downloadHandler.text);
				tcs.TrySetResult(result);
			});
			return tcs.Task;
		}
	}
}
